package com.hdw.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by liuchunchun on 2018/11/28.
 */
public class CommonStringUtil extends org.apache.commons.lang3.StringUtils {

    public static final char UNDERLINE = '_';

    /**
     * 驼峰格式字符串转换为下划线格式字符串
     *
     * @param param
     * @return
     */
    public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 将字符串的第一位转为小写
     * @param str 需要转换的字符串
     * @return 转换后的字符串
     */
    public static String toLowerCaseFirstOne(String str) {
        if (Character.isLowerCase(str.charAt(0))) {
            return str;
        } else {
            char[] chars = str.toCharArray();
            chars[0] = Character.toLowerCase(chars[0]);
            return new String(chars);
        }
    }

    /**
     * 将字符串的第一位转为大写
     * @param str 需要转换的字符串
     * @return 转换后的字符串
     */
    public static String toUpperCaseFirstOne(String str) {
        if (Character.isUpperCase(str.charAt(0))) {
            return str;
        } else {
            char[] chars = str.toCharArray();
            chars[0] = Character.toUpperCase(chars[0]);
            return new String(chars);
        }
    }

    /**
     * 分割文本并去除空项 anzz
     *
     * @param str   文本
     * @param regex 分割规则正则表达式
     * @return
     */
    public static List<String> splitString(String str, String regex) {
        if (StringUtils.isEmpty(str)) return new ArrayList<>(0);
        String[] split = str.split(regex);
        List<String> changeClasss = new ArrayList<>(Arrays.asList(split));
        ListIterator<String> iterator = changeClasss.listIterator();

        while (iterator.hasNext()) {
            String next = iterator.next();
            if (StringUtils.isEmpty(next))
                iterator.remove();
        }
        return changeClasss;
    }

    /**
     * 下划线格式字符串转换为驼峰格式字符串
     *
     * @param param
     * @return
     */
    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == UNDERLINE) {
                if (++i < len) {
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 下划线格式字符串转换为驼峰格式字符串2
     *
     * @param param
     * @return
     */
    public static String underlineToCamel2(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        StringBuilder sb = new StringBuilder(param);
        Matcher mc = Pattern.compile("_").matcher(param);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
        }
        return sb.toString();
    }

    public static String getTipMsg(int type) {
        String tipMsg = "";
        switch (type) {
            case -1:
                tipMsg = "编码重复";
                break;
            case -2:
                tipMsg = "名称重复";
                break;
            default:
                tipMsg = type+"";
                break;
        }
        return tipMsg;
    }

    /*
    * 判空操作，有一个是空则返回true
    * */
    public static boolean isNull(Object ... params){
        boolean result = false;

        List<Boolean> resultList = new ArrayList<Boolean>();
        for (Object param : params) {
            boolean resultTemp = false;

            if (param == null) {
                resultTemp = true;
            }

            if (param instanceof String) {
                if (param.equals("")) {
                    resultTemp = true;
                }
            } else if (param instanceof List) {
                if (((List) param).isEmpty()) {
                    resultTemp = true;
                }
            }

            resultList.add(resultTemp);
        }

        for (Boolean aBoolean : resultList) {
            result = result || aBoolean;
        }

        return result;
    }

    /**
     * 获取字符串中两个字符之间的内容
     * @param str
     * @param start 开始字符
     * @param end   结束字符
     * @param isSpecial 是否需要转义
     * @return
     */
    public static List<String> getStrContainData(String str, String start, String end, boolean isSpecial){
        List<String> result = new ArrayList<>();
        String start_new="",end_new="";
        String startArr[] = start.split(""),endArr[]=end.split("");
        if(isSpecial){
            for(int i=0;i<startArr.length;i++) {
                start_new += "\\" + startArr[i];
            }
            for(int i=0;i<endArr.length;i++) {
                end_new += "\\" + endArr[i];
            }
        } else {
            start_new=start;
            end_new=end;
        }
        String regex = start_new + "(.*?)" + end_new;
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        while(matcher.find()){
            String key = matcher.group(1);
            if(!key.contains(start_new) && !key.contains(end_new)){
                result.add(key);
            }
        }
        return result;
    }

    /**
     * 判断字符串是否为空
     *
     * @param string
     * @return
     */
    public static boolean isEmpty(String string) {
        if (string == null || string.length() ==0|| string.equals("")) {
            return true;
        } else {
            return false;
        }
    }

    public static void main1(String[] args) {
        //System.out.println(underlineToCamel("id_tet"));
        //System.out.println(underlineToCamel("idTet"));
        String str = "是打发${{year}}大水发打发顺丰${{name}}大饭馆 人头而我去日期二无奇热网吃饭VB发${{code}}大厦第三方第三方儿 按按 drqer //的说法放 而我若群 日期二无";
        List<String> backStr = getStrContainData(str,"${{","}}",true);
        System.out.println(isNum("123.45.23"));
    }

    public static boolean isNum(String str) {
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        return pattern.matcher(str).matches();
    }

    public static List<String> asList(String idFuList) {
        if (idFuList == null) {
            return null;
        }
        List<String> returnList = new ArrayList<>();

        List<String> strings = Arrays.asList(idFuList.split(","));
        for (String string : strings) {
            if (string != null && !"".equals(string)) {
                returnList.add(string);
            }
        }

        return returnList;
    }

    private final static int[] li_SecPosValue = { 1601, 1637, 1833, 2078, 2274,
            2302, 2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858,
            4027, 4086, 4390, 4558, 4684, 4925, 5249, 5590 };
    private final static String[] lc_FirstLetter = { "a", "b", "c", "d", "e",
            "f", "g", "h", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "w", "x", "y", "z" };

    /**
     * 取得给定汉字串的首字母串,即声母串
     * @param str 给定汉字串
     * @return 声母串
     */
    public static String getAllFirstLetter(String str) {
        if (str == null || str.trim().length() == 0) {
            return "";
        }

        String _str = "";
        for (int i = 0; i < str.length(); i++) {
            _str = _str + getFirstLetter(str.substring(i, i + 1));
        }

        return _str.toUpperCase();
    }

    /**
     * 取得给定汉字的首字母,即声母
     * @param chinese 给定的汉字
     * @return 给定汉字的声母
     */
    public static  String getFirstLetter(String chinese) {
        if (chinese == null || chinese.trim().length() == 0) {
            return "";
        }
        chinese = conversionStr(chinese, "GB2312", "ISO8859-1");

        if (chinese.length() > 1) // 判断是不是汉字
        {
            int li_SectorCode = (int) chinese.charAt(0); // 汉字区码
            int li_PositionCode = (int) chinese.charAt(1); // 汉字位码
            li_SectorCode = li_SectorCode - 160;
            li_PositionCode = li_PositionCode - 160;
            int li_SecPosCode = li_SectorCode * 100 + li_PositionCode; // 汉字区位码
            if (li_SecPosCode > 1600 && li_SecPosCode < 5590) {
                for (int i = 0; i < 23; i++) {
                    if (li_SecPosCode >= li_SecPosValue[i]
                            && li_SecPosCode < li_SecPosValue[i + 1]) {
                        chinese = lc_FirstLetter[i];
                        break;
                    }
                }
            } else // 非汉字字符,如图形符号或ASCII码
            {
                chinese = conversionStr(chinese, "ISO8859-1", "GB2312");
                chinese = chinese.substring(0, 1);
            }
        }

        return chinese;
    }

    /**
     * 字符串编码转换
     * @param str 要转换编码的字符串
     * @param charsetName 原来的编码
     * @param toCharsetName 转换后的编码
     * @return 经过编码转换后的字符串
     */
    private static String conversionStr(String str, String charsetName,String toCharsetName) {
        try {
            str = new String(str.getBytes(charsetName), toCharsetName);
        } catch (Exception ex) {
            System.out.println("字符串编码转换异常：" + ex.getMessage());
        }
        return str;
    }
    /*去掉字符串中的特殊字符*/
    public static String updateStringCode(String str) {
        String regEx = "[`~!@#$%^&*()\\-+={}':;,\\[\\].<>/?￥%…（）_+|【】‘；：”“’。，、？\\s]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }
}
